// 编码库
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import {addCodeLibrary, getU8Token, editCodeLibrary, getSearchBrand} from '../../api';
import action from '../../store/actions/codeLibrary';
import {Drawer, Button, Input, Form, Select, Radio} from 'antd';
import MyUpload from './MyUpload';
import './Header.scss';

const {Option} = Select;

class CodeHeader extends Component {

  state = {
    visible: false,
    add: false,
    // 模糊搜索开始
    data: [],
    value: undefined,
    // 模糊搜索结束
    iconLoading: false
  };

  IconLoadingChange = () => {
    this.setState(prevState => {
      return {
        iconLoading: !prevState.iconLoading
      };
    });
  };

  showDrawer = () => {
    this.props.IS_MODIFY(false);
    this.setState({
      visible: true,
      add: true
    });
    this.props.form.resetFields();
    this.props.GET_SINGLE_CODE(0);
  };

  onClose = () => {
    this.props.IS_MODIFY(false);
    this.setState({
      visible: false
    });
    this.props.form.resetFields();
  };

  handleOk = e => {
    e.preventDefault();
    console.log(e);
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.IconLoadingChange();
        const {isModify} = this.props;
        const u8Tokon = '';
        getU8Token().then(res => {
          const [token, cate_code] = [res.data, this.props.cate_code];
          if (isModify) {
            // ********************点击的是修改
            let {invcode, ...falg} = values;
            const temp = {token, ...falg, unitgroup_type: '0'};
            editCodeLibrary(values.invcode, temp)
              .then(res => {
                this.props.GET_CODELIBRARY_INFO(cate_code, this.props.currentPage, 10);
                this.IconLoadingChange();
                this.onClose();
              }).catch(err => {
              console.log(err);
            });
          } else {
            // ********************点击事增加
            let {...flag} = values;

            const temp = {cate_code, ...flag, unitgroup_type: '0'};
            console.log(temp);
            addCodeLibrary(temp)
              .then(res => {
                this.props.GET_CODELIBRARY_INFO(cate_code, this.props.currentPage, 10);
                this.IconLoadingChange();
                this.onClose();
              }).catch(err => {
              console.log(err);
            });
          }

        }).catch(err => {
          console.log(err);
        });
      }
    });
  };
  // 模糊搜索开始
  handleSearch = value => {
    if (value) {
      // 做ajax 处理
      console.log(value);
      getSearchBrand(value).then(res => {
        let data = res.data;
        this.setState({data});
      }).catch(err => {
        console.log(err);
      });

    } else {
      this.setState({data: []});
    }
  };

  handleChange = value => {
    this.setState({value});
  };

  componentDidMount() {
    // 获取品牌数据
    const {GET_ALL_BRAND} = this.props;
    GET_ALL_BRAND();
  }

  shouldComponentUpdate(nextProps, nextState, nextContext) {
    if (nextProps.isModify) {
      nextState.visible = true;
    }
    return true;
  }


  render() {
    const {data} = this.state;
    const {isSelected, allBrands, allMeasure, cate_code} = this.props;
    const {getFieldDecorator} = this.props.form;
    const {
      brand,
      id,
      invcode,
      key,
      main_measure,
      name,
      specs
    } = this.props.aData;
    console.log(this.props.aData);

    return (
      <>
        <div className='MaterialGroup__head'>
          <h3>编码库</h3>
          <div className={'operation'}>
            <MyUpload/>
            <Button type="primary" onClick={this.showDrawer} disabled={!isSelected}>增加</Button>
          </div>
        </div>
        {/*抽屉开始*/}
        <Drawer
          width={500}
          title="编码"
          placement="right"
          closable={true}
          onClose={this.onClose}
          visible={this.state.visible}
        >

          <Form className="drawer-form" onSubmit={this.handleOk}>

            <Form.Item label='存货名称'>
              {getFieldDecorator('name', {
                initialValue: name || '',
                rules: [{
                  required: true,
                  message: '请填写存货名称...'
                }]
              })(
                <Input placeholder='存货名称'/>
              )}
            </Form.Item>

            <Form.Item label='存货编码'>
              {getFieldDecorator('invcode', {
                initialValue: invcode || cate_code,
                rules: [{
                  required: true,
                  message: '请填写存货编码...'
                }]
              })(
                <Input placeholder='存货编码' disabled={this.props.isModify}/>
              )}
            </Form.Item>

            <Form.Item label='品牌名称'>
              {getFieldDecorator('brand', {
                initialValue: brand || [],
                rules: [{
                  required: true,
                  message: '请选择品牌...'
                }]
              })(
                <Select
                  showSearch
                  value={this.state.value}
                  defaultActiveFirstOption={false}
                  showArrow={false}
                  filterOption={false}
                  onSearch={this.handleSearch}
                  onChange={this.handleChange}
                  notFoundContent={null}
                  placeholder='品牌名称'
                >
                  {
                    data && data.map(item => (
                      <Option key={item.code} value={item.code}>{item.brand_title}</Option>
                    ))
                  }
                </Select>
              )}
            </Form.Item>
            {/*{*/}
            {/*  this.props.isModify*/}
            {/*    ?*/}
            {/*    <Form.Item label='品牌名称'>*/}
            {/*      {getFieldDecorator("brand", {*/}
            {/*        initialValue: brand || [],*/}
            {/*        rules: [{*/}
            {/*          required: true,*/}
            {/*          message: "请选择品牌..."*/}
            {/*        }]*/}
            {/*      })(*/}
            {/*        <Select*/}
            {/*          placeholder='品牌名称'*/}
            {/*        >*/}
            {/*          {*/}
            {/*            allBrands && allBrands.map(item => (*/}
            {/*              <Option key={item.code} value={item.code}>{item.brand_title}</Option>*/}
            {/*            ))*/}
            {/*          }*/}
            {/*        </Select>*/}
            {/*      )}*/}
            {/*    </Form.Item>*/}
            {/*    :*/}
            {/*    <Form.Item label='品牌名称'>*/}
            {/*      {getFieldDecorator("brand", {*/}
            {/*        initialValue: brand || [],*/}
            {/*        rules: [{*/}
            {/*          required: true,*/}
            {/*          message: "请选择品牌..."*/}
            {/*        }]*/}
            {/*      })(*/}
            {/*        <Select*/}
            {/*          showSearch*/}
            {/*          value={this.state.value}*/}
            {/*          defaultActiveFirstOption={false}*/}
            {/*          showArrow={false}*/}
            {/*          filterOption={false}*/}
            {/*          onSearch={this.handleSearch}*/}
            {/*          onChange={this.handleChange}*/}
            {/*          notFoundContent={null}*/}
            {/*          placeholder='品牌名称'*/}
            {/*        >*/}
            {/*          {*/}
            {/*            data && data.map(item => (*/}
            {/*              <Option key={item.code} value={item.code}>{item.brand_title}</Option>*/}
            {/*            ))*/}
            {/*          }*/}
            {/*        </Select>*/}
            {/*      )}*/}
            {/*    </Form.Item>*/}
            {/*}*/}


            <Form.Item label='规格型号'>
              {getFieldDecorator('specs', {
                initialValue: specs || '',
                rules: [{
                  required: true,
                  message: '请填写规格型号...'
                }]
              })(
                <Input placeholder='规格型号'/>
              )}
            </Form.Item>

            <Form.Item label='单位'>
              {getFieldDecorator('main_measure', {
                initialValue: main_measure || [],
                rules: [{
                  required: true,
                  message: '请选择单位...'
                }]
              })(
                <Select
                  placeholder='请选择单位'
                  disabled={this.props.isModify}
                >
                  {
                    allMeasure && allMeasure.map(item => (
                      <Option key={item.code} value={item.code}>{item.name}</Option>
                    ))
                  }
                </Select>
              )}
            </Form.Item>

            <Form.Item>
              <div id='drawer-form-buttons'>
                <Button type="primary" className="drawer-form-button" onClick={this.onClose}>取 消</Button>
                <Button type="danger" className="rawer-form-button" onClick={this.handleOk}
                        loading={this.state.iconLoading}>确 定</Button>
              </div>
            </Form.Item>

          </Form>
        </Drawer>
        {/*抽屉结束*/}
      </>
    );
  }

}

const mapStateToProps = state => {
  return {
    isSelected: state.codeLibrary.isSelected,
    cate_code: state.codeLibrary.cate_code,
    isModify: state.codeLibrary.isModify,
    aData: state.codeLibrary.aData,
    allBrands: state.codeLibrary.allBrands,
    allMeasure: state.codeLibrary.allMeasure
  };
};
const WrappedNormalLoginForm = Form.create()(CodeHeader);
export default connect(mapStateToProps, action)(withRouter(WrappedNormalLoginForm));
